package com.cychat.mall.controller;

import com.Cychat.commons.entity.ResultMessage;
import com.Cychat.commons.entity.pojo.Favorite;
import com.Cychat.commons.entity.pojo.Product;
import com.Cychat.commons.entity.pojo.ShoppingCart;
import com.cychat.mall.service.FavoriteService;
import com.cychat.mall.service.ProductService;
import com.cychat.mall.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Auther: 刘俊  <br/>
 * Date: 2025-10-31:下午 3:51  <br/>
 * Description: 收藏控制器
 */
@RestController
@RequestMapping("/api/mall")
@CrossOrigin
public class FavoriteController {
    @Autowired
    FavoriteService favoriteService;
    @Autowired
    ProductService productService;
    @Autowired
    ShoppingCartService shoppingCartService;
    // 根据用户ID和商品ID收藏商品
    @PostMapping("/favorite/product/{userId}")
    public ResultMessage<String> addFavorite(
            @PathVariable("userId")Long userId,
            @RequestParam("productId")Integer productId) {
        try {
            if (userId == null || productId == null) {
                return ResultMessage.error("用户ID或商品ID不能为空");
            }
            favoriteService.addFavorite(userId, productId);
            return ResultMessage.success("收藏成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMessage.error("收藏失败: " + e.getMessage());
        }
    }

    //根据收藏ID删除收藏商品
    @DeleteMapping("/favorite/delete/{userId}")
    public ResultMessage<String> deleteFavorite(
            @PathVariable("userId")Long userId,
            @RequestParam("productId")Integer productId) {
        try {
            if (userId == null || productId == null) {
                return ResultMessage.error("用户ID或商品ID不能为空");
            }
            favoriteService.deleteFavorite(userId, productId);
            return ResultMessage.success("取消收藏成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMessage.error("取消收藏失败: " + e.getMessage());
        }
    }

    //根据用户ID查询商品是否被收藏
    @GetMapping("/favorite/search/{userId}")
    public ResultMessage<Boolean> isFavorite(
            @PathVariable("userId")Long userId,
            @RequestParam("productId")Integer productId) {
        try {
            if (userId == null || productId == null) {
                return ResultMessage.error("用户ID或商品ID不能为空");
            }
            boolean isFavorite = favoriteService.isFavorite(userId, productId);
            return ResultMessage.success(isFavorite);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMessage.error("查询收藏状态失败: " + e.getMessage());
        }
    }

    //根据用户ID查询收藏商品列表,从商品列表中通过targetId,筛选查询type为product的商品列表
    @GetMapping("/favorite/list/{userId}")
    public ResultMessage<List<Product>> getFavoriteList(
            @PathVariable("userId")Long userId) {
        try {
            if (userId == null) {
                return ResultMessage.success(List.of());
            }
            List<Favorite> favoriteList = favoriteService.getFavoriteList(userId);
            List<Product> productList = favoriteList.stream()
                    .filter(favorite -> "product".equals(favorite.getType()))
                    .map(Favorite::getTargetId)
                    .map(productId -> productService.getById(productId))
                    .filter(product -> product != null) // 防止商品已删除导致 null
                    .collect(Collectors.toList());
            return ResultMessage.success(productList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMessage.error("获取收藏列表失败: " + e.getMessage());
        }
    }

    //传入userId和productId，将商品添加到购物车
    @PostMapping("/favorite/addToCart/{userId}")
    public ResultMessage<String> addToCart(
            @PathVariable("userId")Long userId,
            @RequestParam("productId")Integer productId) {
        try {
            if (userId == null || productId == null) {
                return ResultMessage.error("用户ID或商品ID不能为空");
            }
            // 校验商品是否存在
            Product product = productService.getById(productId);
            if (product == null) {
                return ResultMessage.error("商品不存在: productId=" + productId);
            }
            //检验购物车中是否已存在该商品，若存在则更新数量，否则新增购物车项
             ShoppingCart cartItem = shoppingCartService.getCartItem(userId, productId);
            if (cartItem != null) {
                // 购物车中已存在该商品，更新数量
                shoppingCartService.updateCartItemQuantity(userId, productId, cartItem.getQuantity() + 1);
            } else {
                // 购物车中不存在该商品，新增购物车项
                // 调用服务层方法添加到购物车
                favoriteService.addToCart(userId, productId);
            }

            return ResultMessage.success("添加到购物车成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMessage.error("添加到购物车失败: " + e.getMessage());
        }
    }
}
